package vehicle

import (
	v1 "gitee.com/sweetsunnyflower/carpooling-server-go/app/http/controllers/api/v1"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/models/vehicle_model"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/policies"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/requests"
	"github.com/gofiber/fiber/v2"
	"github.com/spf13/cast"
)

type VehicleModelsController struct {
	v1.BaseController
}

func (controller *VehicleModelsController) Index(c *fiber.Ctx) error {

	vehicleModels := vehicle_model.GetByBrandId(cast.ToUint64(c.Query("brand_id")))
	return controller.Json(c, vehicleModels)
}

func (controller *VehicleModelsController) Show(c *fiber.Ctx) error {
	vehicleModelModel := vehicle_model.Get(cast.ToUint64(c.Query("id")))
	if vehicleModelModel.ID == 0 {
		return controller.NotFound(c)
	}
	return controller.Json(c, vehicleModelModel)
}

func (controller *VehicleModelsController) Store(c *fiber.Ctx) error {

	request := new(requests.VehicleModelRequest)

	if errors := requests.ValidateVehicleModel(c, request); len(errors) > 0 {
		return controller.ValidationError(c, errors)
	}

	vehicleModelModel := vehicle_model.VehicleModel{
		// FieldName:      request.FieldName,
	}
	vehicleModelModel.Create()
	if vehicleModelModel.ID > 0 {
		return controller.Success(c)
	} else {
		return controller.Faield(c, "创建失败")
	}
}

func (controller *VehicleModelsController) Update(c *fiber.Ctx) error {

	vehicleModelModel := vehicle_model.Get(cast.ToUint64(c.Query("id")))
	if vehicleModelModel.ID == 0 {
		return controller.NotFound(c)
	}

	userId := controller.Auth(c)
	if ok := policies.CanModifyVehicleModel(userId, vehicleModelModel); !ok {
		return controller.Forbidden(c)
	}

	request := new(requests.VehicleModelRequest)

	if errors := requests.ValidateVehicleModel(c, request); len(errors) > 0 {
		return controller.ValidationError(c, errors)
	}

	// vehicleModelModel.FieldName = request.FieldName
	rowsAffected := vehicleModelModel.Save()
	if rowsAffected > 0 {
		return controller.Success(c)
	} else {
		return controller.Faield(c, "更新失败")
	}
}

func (controller *VehicleModelsController) Delete(c *fiber.Ctx) error {

	vehicleModelModel := vehicle_model.Get(cast.ToUint64(c.Query("id")))
	if vehicleModelModel.ID == 0 {
		return controller.NotFound(c)
	}

	userId := controller.Auth(c)

	if ok := policies.CanModifyVehicleModel(userId, vehicleModelModel); !ok {
		return controller.Forbidden(c)
	}

	rowsAffected := vehicleModelModel.Delete()
	if rowsAffected > 0 {
		return controller.Success(c)
	}

	return controller.Faield(c, "删除失败")
}
